<template>
  <div class="app-container">
    <el-form  size="small" :inline="true">
      <el-form-item>
        <!-- <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery('userResult')"
          >进行绑定关系的识别验证</el-button
        > -->
        <el-button
          type="primary"
          icon="el-icon-full-screen"
          size="mini"
          @click="handleQuery('allResult')"
          >陈列识别</el-button
        >
        <!-- <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleOilStain()"
          >图片油污检测</el-button
        >
        <el-button
          type="warning"
          icon="el-icon-search"
          size="mini"
          @click="handleOilStainValueSetting()"
          >油污阈值设置</el-button
        > -->
        <el-button
          type="primary"
          icon="el-icon-upload"
          size="mini"
          @click="handleShelter()"
          >图片遮挡检测</el-button
        >
        <!-- <el-button
          type="warning"
          icon="el-icon-setting"
          size="mini"
          @click="handleShelterValueSetting()"
          >遮挡阈值设置</el-button
        > -->
      </el-form-item>
    </el-form>
    <!-- <div>油污算法版本：{{ this.oilStainVersion }}</div> -->

    <!-- 算法识别弹窗 -->
    <el-dialog
      v-loading="loading"
      :visible.sync="dialogOpen"
      :close-on-click-modal="false"
      @close="cancel"
      width="800px"
      append-to-body
    >
      <div style="text-align: center;">
        <div style = "font-size: 24px;font-weight: border;color: #333;padding: 24px 0 16px;margin: 0;">陈列识别</div>
        <p style="color: rgba(0,0,0,0.65);font-size: 18px;padding: 0 0 24px;margin: 0;">选择以下任何一种方式开始图片识别。</p>
        <div style="width: 100%;height: 54px;border-radius: 4px;border: 1px solid #dcdcdc;margin-bottom: 24px;">
          <div class="urlInput">
            <el-input id="input1" v-model="recognitionForm.imageUrl"  placeholder="请输入或粘贴图片地址" class="inputStyle"/>
          </div>
          <div style="width: 54px;float: right;cursor: pointer;background-color: #f84949;height: 100%;border-radius: 0 4px 4px 0;align-items: center;justify-content: center;display: flex;" @click="handleUrlRec" >
            <img src="@/assets/images/recSearch.svg" alt="light" style="width: 20px;height: 20px;">
          </div>
        </div>
        <div  style="color:#000;background-color: #eee;border:2px dashed #ccc;padding:24px 12px;cursor:pointer;" tabindex="0" @click="handleClickBtn" @dragover="dragover"
        @dragleave="dragleave"
        @drop="drop">
          <div style="margin-bottom: 24px;align-items: center;justify-content: center;display: flex;">
            <img src="@/assets/images/recUploadImg.svg" alt="light" style="width: 75px;height: 75px;">
          </div>
          <p style="font-size: 16px;color:#000;font-weight: 500;margin:12px 0;">拖放或粘贴图片在此区域的任何位置</p>
          <p style="font-size: 16px;color:#000;font-weight: 500;margin:12px 0;">或</p>
          <button class="labelStyle" >
            <input type="file" id="file-btn" accept=".jpg,.png,.jpeg" autocomplete="off" tabindex="-1" style="display: none;"  ref="packageFile"  @change="handFileChange"> 
            上传一张图片
          </button>
        </div>
        <p style="font-size: 14px;margin:12px 0;user-select: none;color:rgba(0,0,0,0.65)">JPG或PNG图片，文件大小必须小于50MB。</p>

      </div>
    </el-dialog>
    <!-- 图片遮挡弹窗 -->
    <el-dialog
      v-loading="shelterLoading"
      :visible.sync="shelterDialogOpen"
      :close-on-click-modal="false"
      @close="cancel"
      width="820px"
      append-to-body
    >
      <div style="text-align: center;">
        <div style = "font-size: 24px;font-weight: border;color: #333;padding: 24px 0 16px;margin: 0;">遮挡识别</div>
        <p style="color: rgba(0,0,0,0.65);font-size: 18px;padding: 0 0 24px;margin: 0;">1.输入阈值。</p>
        <div style="width: 100%;height: 54px;border-radius: 4px;border: 1px solid #dcdcdc;margin-bottom: 24px;">
          <div class="urlInput2">
            <el-input id="input1" v-model="shelterJudgeForm.threshold"  placeholder="请输入阈值" class="inputStyle"/>
          </div>
        </div>
        <p style="color: rgba(0,0,0,0.65);font-size: 18px;padding: 0 0 24px;margin: 0;">2.选择以下任何一种方式开始图片识别。</p>

        <div style="width: 100%;height: 54px;border-radius: 4px;border: 1px solid #dcdcdc;margin-bottom: 24px;">
          <div class="urlInput">
            <el-input id="input1" v-model="shelterJudgeForm.imageUrl"  placeholder="请输入图片链接,多个链接间用英文逗号分隔,请不要输入空格与汉字" class="inputStyle"/>
          </div>
          <div style="width: 54px;float: right;cursor: pointer;background-color: #f84949;height: 100%;border-radius: 0 4px 4px 0;align-items: center;justify-content: center;display: flex;" @click="handleUrlShelter" >
            <img src="@/assets/images/recSearch.svg" alt="light" style="width: 20px;height: 20px;">
          </div>
        </div>
        <div style="text-align: left;">
          <el-upload
                class="upload-demo"
                ref="upload"
                action="/"
                :on-change="changeShelterFile"
                :on-preview="handlePreview"
                :file-list="shelter_fileList"
                multiple
                :auto-upload="false"
                list-type="picture-card"
              >
              <div slot="file" slot-scope="{file}" class='uploadImg'>
                <img class="el-upload-list__item-thumbnail"
                  style="width: 100%;height: 100%;"
                  :src="file.url" alt
                >
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span
                      class="el-upload-list__item-delete"
                      @click="handleDownload(file)"
                    >
                      <i class="el-icon-download"></i>
                    </span>
                    <span
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                </span>
              </div>
                <el-button slot="trigger" size="small" type="primary" >上传图片</el-button>
          </el-upload>
        </div>
   
        <p style="font-size: 14px;margin:12px 0;user-select: none;color:rgba(0,0,0,0.65)">JPG或PNG图片，文件大小必须小于50MB。</p>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="judgeShelter">识 别</el-button>
      </div>
    </el-dialog>


    <el-dialog
      title="识别结果"
      :visible.sync="logDialog"
      :close-on-click-modal="false"
      width="70%"
      destroy-on-close
      destroy-on-closescope
    >
    <span>算法名称：{{this.algorithm}}</span>
    <span style="margin-left:15px">算法版本：{{this.version}}</span>
    <div ref="canvasBox" class="composeImage" >
      <canvas ref="canvas"></canvas>
    </div>

      <!-- 陈列明细 -->
      <el-table :data="skuList" style="width: 100%">
        <el-table-column label="sku名称" prop="skuName" align="center">
        </el-table-column>
        <el-table-column label="所在层数" prop="skuLayer" align="center">
        </el-table-column>
        <el-table-column label="排面数量" prop="skuNum" align="center">
        </el-table-column>
        <el-table-column label="排面占比" prop="skuRate" align="center">
        </el-table-column>
      </el-table>

      <span slot="footer" class="dialog-footer">
        <el-button @click="logDialog = false">取 消</el-button>
        <el-button type="primary" @click="logDialog = false">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 图片遮挡弹窗 -->
    <!-- <el-dialog
      :title="dialogTitle"
      :visible.sync="shelterDialogOpen"
      :close-on-click-modal="false"
      @close="cancel"
      width="800px"
      append-to-body
    >
      <el-form
        ref="shelterJudgeForm"
        :model="shelterJudgeForm"
        :rules="shelterJudgeFormRules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="项目" prop="projectId">
              <el-select
                v-model="shelterJudgeForm.projectId"
                clearable
                filterable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in project_list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="阈值" prop="threshold">
              <el-input v-model="shelterJudgeForm.threshold" placeholder="请输入阈值"  @input="inputValueChange"  type="number" oninput="if(value > 100)value = 100;if(value<0)value = 0"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图片url" prop="imageUrl">
              <el-input v-model="shelterJudgeForm.imageUrl" placeholder="请输入图片链接,多个链接间用英文逗号分隔,请不要输入空格与汉字"  type="textarea" @input="inputValueChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图片上传">
              <el-upload
                class="upload-demo"
                ref="upload"
                action="/"
                :on-change="changeShelterFile"
                :on-preview="handlePreview"
                :file-list="shelter_fileList"
                multiple
                :auto-upload="false"
                list-type="picture-card"
              >
              <div slot="file" slot-scope="{file}" class='uploadImg'>
                <img class="el-upload-list__item-thumbnail"
                  style="width: 100%;height: 100%;"
                  :src="file.url" alt
                >
                  <span class="el-upload-list__item-actions">
                    <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <span
                      class="el-upload-list__item-delete"
                      @click="handleDownload(file)"
                    >
                      <i class="el-icon-download"></i>
                    </span>
                    <span
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                </span>
              </div>
                <el-button slot="trigger" size="small" type="primary" >上传图片</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="judgeShelter">识 别</el-button>
      </div>
    </el-dialog> -->

    <!-- 遮挡阈值设置-弹框 -->
    <el-dialog
      title="遮挡算法阈值设置"
      :visible.sync="shelterValueSettingDialogOpen"
      @close="cancel"
      width="800px"
      append-to-body
    >
    <el-form
        :model="shelterValueSettingForm"
        label-width="120px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="阈值" prop="threshold">
              <el-input v-model="shelterValueSettingForm.threshold" placeholder="请输入阈值"  @input="inputValueChange"  type="number" oninput="if(value > 100)value = 100;if(value<0)value = 0"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirmSetShelterValue">确 定</el-button>
      </div>
    </el-dialog>


    <!-- 图片放大 -->
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>


  </div>
</template>
 
<script>


import { setInitImg } from '@/utils/url-transfer-file'
import { fabric } from 'fabric'
import { algV4Detect, getAlgListV4, getArithmeticDetail, modifySkuMinImgList, shelterRecognize, setShelterThresholdV4 } from '@/api/arithmetic/arithmetic';
import { listProject } from "@/api/project/project";
import { listSku } from "@/api/sku/sku";
 
export default {
data(){
  return {
    uploadPicNum:0, //上传的图片数量
    dialogImageUrl: '',//放大图片的url
    dialogVisible: false,//点击放大
    layerList:[
      {
        name:'顶层库',
        id:1
      },
      {
        name:'中间层库',
        id:2
      },
      {
        name:'底层库',
        id:3
      },
    ],
    skuSum:0,
    skuList:[],
    fileList: [], // 小图集合 
    shelter_fileList:[], // 遮挡图片集合 
    algorithm:'',//算法名称
    version:'',//算法版本
    currentLog: null, // 当前查看的识别记录
    logDialog: false,
    //表单校验
    algoFormRules: {
      skuName: [{ required: true, message: '请选择', trigger: 'blur' }],
      algMainImg: [{ required: true, message: '请选择', trigger: 'blur' }],
    },
    // 算法列表
    arithmetic_list:[],
    alogSkuId:'',//输入的算法skuId
    // 陈列识别
    loading:false,
    // 图片遮挡检测
    shelterLoading:false,
    //算法详情表单
    algoForm: {
      skuName: '',
      algMainImg: '',
      layer:'',
      algMinImgList: [],
    },
    AlgoDialogTitle:"算法详情",
    addMark:false,
    AlgoDialogOpen:false,
    nowAddFile:'',
    nowMainPicName:'',//当前对应的sku的名称
    imgHeight: 0,
    nowMainPicUrl:'',//当前对应的sku的主图url
    skuPosition:0,
    nowAddUrl:'',//截取的图片的url
    cutPicNum:0,
    minImgListSum:0,//小图组总数
    mainImgUrl: '',//主图url
    number: 0,
    // 商品列表
    sku_list:[],
    // 项目列表
    project_list:[],
    // 算法识别-表单字段
    recognitionForm: {
      projectId: 1, // 项目id
      imageUrl: '', // 输入的图片url
      packageFile: '' // 上传图片文件
    },
    // 识别结果弹窗展示的图片
    showUrl: '',
    // 图片文件上传的url
    picUrl:'',
    //识别结果类型： userResult allResult
    resultType: '',
    // 油污算法版本号
    oilStainVersion: '', 
    // 油污阈值弹窗
    oilStainValueSettingDialogOpen: false,
    // 油污弹窗
    oilStainDialogOpen: false, 
    // 遮挡阈值表单
    shelterValueSettingForm:{
      projectId:''
    },
    // 遮挡阈值弹窗
    shelterValueSettingDialogOpen: false,
    // 遮挡弹窗
    shelterDialogOpen: false, 
    // 算法识别-弹窗标题
    dialogTitle: '图片上传',
    // 算法识别-弹窗开关
    dialogOpen: false,
    // 油污分数判断-表单字段
    oilStainJudgeForm:{
      userId:'',  //用户id
      twoUserId:'',
      threeUserId:'',
      fourUserId:'',
      fiveUserId:'',
      sixUserId:'',
      packageFile: '',
      imageUrl:'',
      picUrl:''
    },
    timer:null,//定时器
    // 遮挡分数判断-表单字段
    shelterJudgeForm:{
      projectId:1, // 项目id
      threshold:'', // 阈值
      imageUrl:'', // 需要识别的图片地址，多个以英文逗号字符分割，url中请勿存在中文或空格
    },

  }
},

  methods: {
    shelterDragover(e) {
      e.preventDefault();
    },
    shelterDragleave() {
    },
    shelterDrop(e) {
      e.preventDefault();
      let fileData = e.dataTransfer.files 
      console.log(fileData)
      this.recognitionForm.packageFile = fileData
      // this.shelterLoading = true
      // this.judgeShelter()
    },
    dragover(e) {
      e.preventDefault();
    },
    dragleave() {
    },
    drop(e) {
      e.preventDefault();
      let fileData = e.dataTransfer.files[0] 
      console.log(fileData)
      this.recognitionForm.packageFile = fileData
      let url = URL.createObjectURL(fileData)
      this.picUrl = url
      this.loading = true
      this.uploadImg()
    },
    dragImg(e){
      console.log(e)
    },
    // 点击上传一张图片按钮
    handleClickBtn(){
      document.getElementById('file-btn').click()
    },
    /** 确认设置遮挡算法阈值 */
    confirmSetShelterValue(){
      if(!this.shelterValueSettingForm.threshold){
        this.$message.warning("请输入您想设置的阈值！")
        return
      }
      const param={
        threshold:parseInt(this.shelterValueSettingForm.threshold)
      }
      setShelterThresholdV4(param).then((res) =>{
        if(res.code === 200){
          this.$message.success("阈值设置成功！")
        }
      }).catch((err) =>{
        this.$message.error("设置失败！原因："+err.message)
      }).finally(() =>{
        this.shelterValueSettingDialogOpen = false
      })
    },
    /** 上传图片-删除 */
    handleRemove(file){   
      var index = this.shelter_fileList.indexOf(file)
      if(index !== -1){
        // this.algoForm.files.splice(index,1)
        this.shelter_fileList.splice(index,1)
      }
    },
    /** 图片下载 */
    handleDownload(file){
      var link = document.createElement("a"); //定义一个a标签
      link.download = file.name; //下载后的文件名称
      link.href = file.url; //需要生成一个 URL 来实现下载
      link.click(); //模拟在按钮上实现一次鼠标点击
      window.URL.revokeObjectURL(link.href);
    },
    /** 图片放大 */
    handlePictureCardPreview(file){
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /** base64转文件 */
    base64ToFile(base64, fileName) {
      let arr = base64.split(",");
      // let mime = arr[0].match(':')[1];
      let mime = 'image/png'
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
    
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], fileName, { type: mime });
    },
    /** 获取算法列表 */
    getAlgoData() {
      const params = {
        pageIndex: 0,
        pageSize: 10000,
        // skuId : this.skuId,
        // layer:0
      }
      getAlgListV4(params)
        .then((res) => {
          this.arithmetic_list = res.data.data
        }).catch((err) =>{
          this.$message.error("算法列表获取失败",err.message)
        })
        .finally(() =>{
          
        })
    },
    /** 确认新增小图 */
    submitForm() {
        if(this.algoForm.skuName == ''){
          this.$confirm('请输入sku名称', '提示', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          })
        }
        
        if(this.algoForm.algMainImg == ''){
          this.$confirm('请上传主图', '提示', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          })
        }
        if(this.addMark === false){
          this.$confirm('请先点击按钮-加入当前截取图片', '提示', {
          distinguishCancelAndClose: true,
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          })
          return
        }
        setInitImg(this.algoForm.packageFile,(file)=>{
          this.algoForm.packageFile=file
          const form = this.algoForm
          const formData = new FormData()
          for(var i=0;i<form.files.length;i++){
            formData.append("files",form.files[i])
          }
          const params = {
            skuId : form.skuId,
            files : formData
          }
          this.uploadLoading=true
          this.$notify({
            title: '提示',
            message: '图片上传中,请稍后…',
            offset: 700,
            duration: 0
          });
          this.dialogFull=true
          modifySkuMinImgList(params).then((res) => {
              this.$message.success('新增小图成功')
              this.$notify.closeAll();//去掉交互框
              this.AlgoDialogOpen = false
            })
            .catch((err) => {
              this.$message.error(err.message)
            })
            .finally(() =>{
              this.dialogFull=false
              this.uploadLoading=false
            })
        }) 
    },
    /** 加入截取图片 */
    addCutPic(file,fileList){
      if(this.nowAddFile){
        this.algoForm.files.push(this.nowAddFile)
        this.addMark = true
        this.minImgListSum++
        this.algoForm.algMinImgList.push(this.nowAddUrl)
        let temp={
          name:this.nowAddUrl,
          url:this.nowAddUrl,
          status:'ready',
          uid:this.cutPicNum
        }
        this.cutPicNum++
        this.fileList.push(temp)
        this.$forceUpdate()
      }else{
        this.$message.info("请先选择一张小图")
        this.AlgoDialogOpen = false
      }


    },
    handldAlgMainImgChange(e) {
      let fileData = e.target.files[0] //这是我们上传的文件
      this.algoForm.algMainImg = fileData
      this.algoForm.packageFile = fileData
      let url = URL.createObjectURL(fileData)
      this.mainImgUrl = url
    },
    changeShelterFile(file,fileList){
      // 限制上传的图片类型
      if(file.raw.type == 'image/jpeg' || file.raw.type == 'image/png'){
        this.shelter_fileList = fileList
        this.uploadPicNum = this.shelter_fileList.length
        // 限制最大上传张数
        if(this.uploadPicNum > 200){
          // 防抖
          if(this.timer){
            // 次数>1时，清空之前的定时器
            clearTimeout(this.timer)
            this.timer = setTimeout(() =>{
              this.$message.warning("当前仅支持200张同时识别，已删除第201张及之后的图片")
            },1000)
          }else{
            // 第一次
            this.timer = setTimeout(() =>{
              this.$message.warning("当前仅支持200张同时识别，已删除第201张及之后的图片")
            },1000)
          }
        this.shelter_fileList.splice(200,1)
        this.uploadPicNum = this.shelter_fileList.length
      }
      }else{
        this.$message.warning("当前仅支持jpg和png格式的图片")
        var index = this.shelter_fileList.indexOf(file)
        this.shelter_fileList.splice(index,1)
      }
    },
    changeFile(file,fileList){
      let fileData=file.raw
      if(this.dialogTitle == '小图情况'){
        this.algoForm.files.push(fileData)
        this.minImgListSum++
      }else{
        this.algoForm.algMinImgList.push(fileData)
        this.minImgListSum++
      }
    },
    handlePreview(file){
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    /** 输入框强制刷新 */
    inputValueChange(){
      this.$forceUpdate()
    },
    /** 点击取消新增小图按钮 */
    handleCancelAdd(){
      this.AlgoDialogOpen = false
      this.algoForm = {}
    },
    /** 点击新增小图按钮 */
    handleAdd() {
      if(!this.alogSkuId){
        this.$message.warning("请先选择算法")
        return
      }
      
      //初始化
      this.mainImgUrl=''
      this.fileList=[]
      this.minImgListSum=0
      this.algoForm = {}
      this.AlgoDialogOpen = true
      this.addMark = false
      //todo根据skuid调用接口获取算法详情和小图信息
      const params = {
        skuId : this.alogSkuId
      }
      getArithmeticDetail(params)
        .then((res) => {
          let resData = res.data
          //初始化数据
          this.algoForm.skuName = resData.name
          this.mainImgUrl=resData.packageUrl
          this.algoForm.layer=resData.layer
          this.algoForm.algMinImgList=resData.pics
          this.algoForm.algMainImg=resData.packageUrl
          this.algoForm.packageFile=resData.packageUrl
          this.minImgListSum=resData.imageCount
          this.algoForm.imgList = resData.pics
          //upload组件需要name属性才能加载
          this.fileList = this.algoForm.imgList.map(item => {
                return {
                  name: item,
                  url: item
                }
          });
          //小图组url转file
          this.algoForm.imgList.forEach((item) => {
            setInitImg(item,(file)=>{
              this.algoForm.files.push(file)
            }) 
          })
        }).catch((err) =>{
          this.$message.error("获取算法详情失败",err.message)
        })
        .finally(() =>{

        })

      this.algoForm.skuId=this.alogSkuId

      //用于存放小图组files
      this.algoForm.files=[]
      //主图url转file
      setInitImg(this.algoForm.packageFile,(file)=>{
        this.algoForm.packageFile=file
          // this.fileList.push(file)
      })
    },
    /** 图片遮挡-判断 */
    async judgeShelter(){
      if(!this.shelterJudgeForm.threshold){
        this.$confirm(`请输入阈值`, '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning',
        })
        return 
      }
      if(this.shelter_fileList.length === 0 && this.shelterJudgeForm.imageUrl == ''){
        this.$confirm(`请上传图片或填写图片链接`, '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning',
        })
        return 
      }


      const formData = new FormData()
      this.shelter_fileList.map((item) =>{
        formData.append('images',item.raw)
      })
      this.$notify({
        title: '提示',
        message: '判断遮挡中…',
        offset: 700,
        duration: 0
      });
      const params = {
        projectId:this.shelterJudgeForm.projectId,
        threshold:this.shelterJudgeForm.threshold,
        imageUrl:this.shelterJudgeForm.imageUrl,
        images : formData
      }
      shelterRecognize(params).then((res) =>{
        if(res.code === 200){
          let text =''
          let shelterNum = 0
          for(var i=0;i<res.data.length;i++){
            // 遮挡红字，正常绿字
            let color = (res.data[i].label ==  '遮挡' ? 'red' : 'green')
            // 统计遮挡次数
            if(res.data[i].label == '遮挡'){
              shelterNum ++
            }
            text = text + `<p>图片${i+1}:${ res.data[i].imageName +'——————————分数:'+`<span style="color:${color}">${res.data[i].score}</span>`+'分——————————结论：'+`<span style="color:${color}">${res.data[i].label }。</span>`}</p>`
          } 
          text = '<p style="font-size:16px;color:#2491fc">共识别 '+res.data.length+' 张图片，其中遮挡 '+shelterNum+' 张,正常 '+(res.data.length - shelterNum)+' 张。<p>'+
          '<p">详细识别结果如下:</p>'+text
          this.$confirm(text,'遮挡识别结果', {
            confirmButtonText: '确定',
            dangerouslyUseHTMLString:true,
            showCancelButton: false,
            type: 'success',
          })
        }
      }).catch((err) => {
        this.$message.error("判断失败！原因："+err.message)
      }).finally(() =>{
        this.$notify.closeAll();//去掉交互框
      })
      
    },
    /** 获取商品列表 */
    getSkuList(){
      const req = listSku({
        pageIndex: 0,
        pageSize: 10000
      })
      .then((res) => {
        if (res && res.total > 0) {
          this.sku_list = res.rows
        }
      }).catch((err) =>{
        this.$message.error("商品获取失败！",err.message)
      })
    },
    //
    handleUrlRec(){
      this.uploadImg()
      this.loading = true
    },
    handleUrlShelter(){
      this.judgeShelter()
      this.shelterLoading = true
    },
    /** 算法识别-接口调用 */
    uploadImg(){
        this.skuPosition = 0
        // 校验是否上传了图片
        if(this.recognitionForm.imageUrl == '' && this.recognitionForm.packageFile == ''){
          this.$confirm(`请上传图片或者填写图片URL(二选一)`, '提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            type: 'warning',
          })
          return 
        }
        console.log(111)
        // 判断是哪种方式上传图片
        if(this.recognitionForm.packageFile){
          this.showUrl=this.picUrl
        }else{
          this.showUrl=this.recognitionForm.imageUrl
        }
        // 参数处理
        const form = this.recognitionForm
        console.log(form)
        let str = ''
        const formData = new FormData()
        Object.keys(form).forEach((key) => {
          if (key !== 'imageUrl' && key !== 'packageFile') {
            str += `&${key}=${form[key]}`
          }
        })
        formData.append('packageFile', form.packageFile)
        formData.append("imageUrl",form.imageUrl)
        const params = {
          url : str ,
          file : formData
        }
        this.$notify({
          title: '提示',
          message: '图片识别中,请稍后…',
          offset: 700,
          duration: 0
        });
        // 获取商品列表
        this.getSkuList()
        // 调用识别接口
        algV4Detect(params)
        .then((res) => {
          this.skuList=[]
          this.dialogOpen = false
          this.logDialog = true
          if(res.code === 0){
              this.$notify.closeAll();//去掉交互框
              if(this.resultType == 'userResult'){
                this.recognitionResult=res.data.userResult
              }else{
                this.recognitionResult=res.data.allResult
              }
              this.version=this.recognitionResult.version
              this.algorithm=this.recognitionResult.algorithm
              this.skuSum=this.recognitionResult.statistics.total_num
              //储存所有识别到sku，skuName为唯一字段
              let skuNameMap = new Map()
              this.recognitionResult.results.forEach((item) =>{
                if(!skuNameMap.has(item.skuName)){
									skuNameMap.set(item.skuName,1)
								}else{
									skuNameMap.set(item.skuName,skuNameMap.get(item.skuName)+1)
								}
              })

              //建立skuList模板
              for(var i=0;i<skuNameMap.size;i++){
								let temp={
                  skuName:'',
                  skuNum:0,
                  skuRate:'',
                  skuLayer:[]
								}
								this.skuList.push(temp)
							}
              console.log(this.skuList)

              //skuList赋值1 - 名称、总量、占比
              skuNameMap.forEach((value,key,self) =>{
                console.log(this.skuList)
                console.log(key)
                console.log(key)


									this.skuList[this.skuPosition].skuName = key
									this.skuList[this.skuPosition].skuNum = value
									this.skuList[this.skuPosition].skuRate = ((value/ this.skuSum) * 100).toFixed(2) + '%'
									this.skuPosition++
							})
              console.log(skuNameMap)
              //skuList赋值2 - 层数
							this.recognitionResult.results.forEach((res) =>{
								for(var i=0;i<this.skuList.length;i++){
									if( this.skuList[i].skuName == res.skuName && !this.skuList[i].skuLayer.includes(res.layer)){
                    if(this.skuList[i].skuLayer.length !== 0){
                      this.skuList[i].skuLayer.push(',')
                      this.skuList[i].skuLayer.push(res.layer)
                    }else{
                      this.skuList[i].skuLayer.push(res.layer)
                    }
                      // skuList[i].name = res.customerSkuName
									}
								}
							})

              console.log(this.recognitionResult.results)
          }
        }).catch((err) =>{
          this.$message.error("识别失败！",err.message)
        })
        .finally(() => {
          this.loading = false
          this.showLog() // canvas画布绘制
          this.getAlgoData() // 获取算法列表
        })
    },
    /**
     * 查看
     * @param {Object} log  当前日志信息
     */
     async showLog() {
      this.$nextTick(() => {
        // const h = 500
        const h=1000
        this.$refs.canvasBox.style.height = h + 'px'
        //对图片进行渲染-图像文件的加载是异步的，所有对Image的后续操作都要在回调中完成
        fabric.Image.fromURL(
          this.showUrl,
          (img) => {
            let w
            img.set({ selectable: false })
            img.scaleToWidth(860)  //指定宽度
            img.scaleToHeight(1000)  //指定图片高度
            w = img.width * img.scaleX
            const canvas = new fabric.Canvas(this.$refs.canvas, {
              width: w,
              height: h,
              centeredRotation: true,
            })
            canvas.add(img)
            let results = []
            try {
              results = this.recognitionResult.results || []
            //用商品名替换掉算法名
              if(results.length>0){
              results.forEach((item) =>{
                this.sku_list.forEach((skuItem) => {
                    if(item.skuName == skuItem.v4SkuName){
                      item.skuName = item.FeatureScore.toFixed(2)+" "+item.skuName  +" "+item.FeatureScore.toFixed(2) 
                      item.url = skuItem.imageUrl
                      //用于展示在右边主图下方，不需要识别分数
                      item.skuNameShow = skuItem.v4SkuName
                    }
                })

              })
            }
            } catch (error) {}
            // 1 本品 绿色框 2 竞品 红色框 3 未知 蓝色框
            const strokeColors = ['#669933', '#ff6666', '#99CCFF']
            const shadowColors = ['green', 'red', 'blue']
            for (let i = 0; i < results.length; i++) {
              const res = results[i]
              // const loc = res.location
              const loc=results[i]
              // loc.TextName = 
              // if (img.width > img.height) {
              //   let t = loc.top
              //   loc.top = loc.left
              //   loc.left = t
              //   t = loc.width
              //   loc.width = loc.height
              //   loc.height = t
              // }
              loc.top = loc.y * img.scaleY //y
              loc.height = loc.height * img.scaleY
              loc.left = loc.x * img.scaleX   //x
              loc.width = loc.width * img.scaleX
              if (!loc) continue
              const colroI = parseInt(Math.random() * 3)
              const stroke = strokeColors[colroI]
              const shadowColor = shadowColors[colroI]
              const shadow = new fabric.Shadow({ color: shadowColor, blur: 0 })
              const rect = new fabric.Rect({
                ...loc,
                fill: 'transparent',
                strokeWidth: 2,
                stroke,
                lockMovementX: true,
                lockMovementY: true,
                hasControls: false,
                hasBorders: false,
              })
              const text = new fabric.Text(loc.skuName, {
                ...loc,
                fontSize: 14,
                stroke: shadowColor,
              })
              text.set('left', text.left - text.width / 2 + loc.width / 2)
              text.set('top', text.top - text.height)
              const Trect = new fabric.Rect({
                top: text.top,
                left: text.left,
                width: text.width,
                height: text.height,
                fill: '#ffffff',
              })
              const tg = new fabric.Group([Trect, text], {
                lockMovementX: true,
                lockMovementY: true,
                hasControls: false,
                hasBorders: false,
              })
              rect.on('selected', () => {
                  rect.set('stroke', shadowColor)
                  rect.set('strokeWidth', 4)
                  canvas.add(tg)
                    let drawing = document.getElementById('canvasSingle')
                    // if(drawing.getContext){
                      const canvas2 = new fabric.Canvas(this.$refs.canvasSingle, {
                        width: rect.width * 3,
                        height: rect.height * 3,
                        centeredRotation: true,
                      })

                      // var image = new Image()
                      // image.src = this.showUrl
                      // // canvas2.add(img)
                      // let context = drawing.getContext('2d')

                      // context.drawImage(
                      //   image, //要绘制的图像
                      //   rect.left/(562.5/img.width), //源图像x坐标
                      //   rect.top/(1000/img.height), //源图像y坐标
                      //   rect.width/(562.5/img.width), //源图像宽度
                      //   rect.height/(1000/img.height), //源图像高度
                      //   0, //目标区域x坐标
                      //   0, //目标区域y坐标
                      //   rect.width * 3, //目标区域宽度
                      //   rect.height * 3 //目标区域高度
                      // )
                      
                      // let imageUrl = this.$refs.canvasSingle.toDataURL('image/jpeg')
                      // this.nowAddFile = this.base64ToFile(imageUrl,'cut'+this.cutPicNum+'.jpg')
                      // this.nowAddUrl = imageUrl
                      // this.cutPicNum++

                      // //展示主图
                      // if(loc.url){
                      //   this.nowMainPicUrl = loc.url
                      // }else{
                      //   this.nowMainPicUrl = ''
                      // }
                      // if(loc.skuNameShow){
                      //   this.nowMainPicName = loc.skuNameShow
                      // }else{
                      //   this.nowMainPicName = ''
                      // }
              })
              rect.on('deselected', () => {
                // rect.shadow.blur = 0
                // rect.shadow.color = stroke
                rect.set('stroke', stroke)
                rect.set('strokeWidth', 2)
                canvas.remove(tg)
              })
              canvas.add(rect)
            }
            canvas.renderAll()
          },
          { crossOrigin: 'anonymous' }
        )
      })
    },
    /** 算法识别-图片文件上传 */
    handFileChange(e) {
      let fileData = e.target.files[0] 
      console.log(fileData)
      this.recognitionForm.packageFile = fileData
      let url = URL.createObjectURL(fileData)
      this.picUrl = url
      this.loading = true
      this.uploadImg()
    },
    /** 获取项目列表 */
    getProjectList(){
      const params={
        pageNum: 1,
        pageSize: 100,
      }
      listProject(params).then((res) =>{
        if(res.code === 200 && res.rows.length>0){
          this.project_list = res.rows.map((item) =>{
            return {
              name: item.projectName,
              id: item.id
            }
          })
        }
      }).catch((err) =>{
        this.$message.error("项目获取失败!",err.message)
      })
    },
    /** 算法识别-弹框取消 */
    cancel(){
      this.dialogOpen = false
      this.shelterDialogOpen = false
      this.shelterValueSettingDialogOpen = false
    },
    /** 搜索按钮操作 */
    handleQuery(type) {
      // 当项目列表为空时，获取
      // if(this.project_list.length === 0){
      //   this.getProjectList()
      // }
      this.recognitionForm.projectId=1
      this.recognitionForm.imageUrl=''
      this.picUrl=''
      this.recognitionForm.packageFile=''
      this.dialogOpen=true
      this.resultType=type
    },
    /** 图片遮挡检测按钮-点击 */ 
    handleShelter(){
      // if(this.project_list.length === 0){
      //   this.getProjectList()
      // }
      this.shelterDialogOpen = true
      this.shelterJudgeForm.projectId = 1
      this.shelterJudgeForm.threshold = ''
      this.shelterJudgeForm.imageUrl = ''
      this.shelter_fileList = []
    },
    /** 图片油污检测按钮-点击 */ 
    handleOilStain(){
      this.oilStainDialogOpen = true
      this.oilStainJudgeForm.imageUrl = ''
      this.oilStainJudgeForm.packageFile = ''
      this.oilStainJudgeForm.picUrl = ''
    },
    /** 油污阈值设置 */
    handleOilStainValueSetting(){
      this.oilStainValueSettingDialogOpen = true
      this.oilStainValueSettingForm = {
        userId:'',  //用户id
        twoUserId:'',
        threeUserId:'',
        fourUserId:'',
        fiveUserId:'',
        sixUserId:'',
        enable:'', //是否启用算法识别 true false
        sieveEnable:'', // 是否启用有无检测 true false
        sieveThreshold:'' //  油污阈值
      }
    },
    /** 遮挡阈值设置 */
    handleShelterValueSetting(){
      this.shelterValueSettingDialogOpen = true
      this.shelterValueSettingForm = {
        threshold:'',
      }
    }

  }
}
;
  // 获取点击上传  选择的文件
  // function selectFile(e) {
  //   // 通过 e.target.files 获取到选择的文件 此处默认选择一个文件
  //   console.log('获取点击上传的文件---',e.dataTransfer.files[0]);
  //   // 第二次验证选择的文件类型是否正确
  //   if(e.target.files[0].type == 'application/msword' || e.target.files[0].type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
  //     file = e.target.files[0]
  //   } else {
  //     alert('请选择正确的文件类型')
  //   }
  // }

  // 拖拽上传获取对应文件
  // let dropBox=document.querySelector('#drop');
  // console.log(dropBox)
  //     // 当文件在目标元素内移动时
  //     dropBox.addEventListener('dragover',function(e){
  //       // 阻止事件冒泡
  //       e.stopPropagation();
  //       // 阻止默认事件（与drop事件结合，阻止拖拽文件在浏览器打开的默认行为）
  //       e.preventDefault();
  //     })
  //     // 当拖拽文件在目标元素内松开时
  //     dropBox.addEventListener('drop',function(e){
  //       // 阻止事件冒泡
  //       e.stopPropagation();
  //       // 阻止默认事件（与dragover事件结合，阻止拖拽文件在浏览器打开的默认行为）
  //       e.preventDefault();
  //       // 获取拖拽上传的文件（files是个数组 此处默认限制只能上传一个）
  //       console.log('获取拖拽上传的文件---',e.dataTransfer.files[0]);
  //       // 第二次验证选择的文件类型是否正确
  //       if(e.dataTransfer.files[0].type == 'application/msword' || e.dataTransfer.files[0].type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
  //         file = e.dataTransfer.files[0]
  //       } else {
  //         alert('请选择正确的文件类型')
  //       }
  //     })
</script>
<style lang="scss">
.labelStyle{
  border: 2px solid #333;
  // pointer-events: none;
  border-radius: 2px;
  color: #333;
  font-size: 13px;
  background-color: #fff;
  height: 40px;
  line-height: 26px;
  padding: 0 25px;
  cursor: pointer;
}
.inputStyle{
  width: 100%; 
  height: 52px;
  line-height: 52px;
}
.urlInput2{
  float: left;
  height: 100%;
  width: 100%;
  position: relative;
}
.urlInput{
  float: left;
  height: 100%;
  width: calc(100% - 54px);
  position: relative;
}
.el-input--medium .el-input__inner{
  height: 52px;
  line-height: 52px;
  font-size: 14px;
}
.el-message-box {
  display: inline-block;
    width: 820px;
    padding-bottom: 10px;
    vertical-align: middle;
    background-color: #FFFFFF;
    border-radius: 4px;
    border: 1px solid #e6ebf5;
    font-size: 18px;
    -webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    text-align: left;
    overflow: hidden;
    -webkit-backface-visibility: hidden;
    backface-visibility: hidden;
}
</style>
